#!/usr/bin/env python3
# Created by han on 2016/6/21
import sys, os, pickle,time
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from conf import db_conf,log_conf
from module import school, maker, public
TEACHER_FILE = db_conf.DB_BASE + "/" + "teacher.db"
# TEACHER_DB = db_conf.T_DB_BASE
# STUDENT_DB = db_conf.S_DB_BASE
COURSE_FILE = db_conf.DB_BASE+ "/" + "course.db"
STUDENT_DB = db_conf.STUDENT_DB_BASE

class Students:
    """
    创建和学生有关的内容
    选课
    上课
    """
    def __init__(self, name,passwd):
        self.name = name       #学生名字
        self.passwd = passwd   #学生密码
        self.exp = 0           #经验值
        self.timetable = []    #课程表

    def add_course(self, coure):
        """
        选课
        :return:
        """
        # db_status = os.path.exists(STUDENTS_FILE)#判断是否有学生的文件
        # if not db_status:
        #     self.timetable.append(course_obj)#没有，直接将选的课程添加到空列表中
        #
        # else:#如果已经有学生文件了
        # stu_db = db_conf.DB_BASE+"/" + self.name
        stu_db = STUDENT_DB + "/" + self.name
        with open(stu_db,"rb") as stu_file_raw:
            students_obj = pickle.load(stu_file_raw)#读取序列化文件
        for i in self.timetable:#由于tietable缓存中可能存放着多个课程，需要循环，一个一个添加
            students_obj.timetable.append(i)#将这个用户的课程表数据再加一门课程对象
        with open(stu_db, "wb") as stu_file:
            pickle.dump(students_obj, stu_file)  # 然后将这个用户对象再存入文件
        return


    def show_course(self):
        """
        展示用户选择的课程
        :return:
        """
        stu_obj = public.load_stu_obj(self.name)#找到用户的文件，提取出用户选择的课程列表
        course_obj_list = stu_obj.timetable#把学生的课程表取出来
        if not course_obj_list:#如果为空就是还没有添加课程
            msg = "您没有选择课程"
            public.color_msg(31, msg, 40)
            return False
        else:
            maker.show_course(course_obj_list)#展示
            return True

    def go(self, exp):
        """
        学生上课函数
        :param exp:获得的经验值
        :return:
        """
        stu_obj = public.load_stu_obj(self.name)
        msg = "学生原经验： {:*^10}".format(stu_obj.exp)
        public.color_msg(35, msg, 40)
        # course_obj_list = stu_obj.timetable
        time.sleep(1)#暂停一下比较真实
        stu_obj.exp += exp
        pickle.dump(stu_obj, open(db_conf.DB_BASE+"/"+self.name,"wb"))
        msg = "学生上课后经验：{:*^10}".format(stu_obj.exp)
        public.color_msg(35, msg, 40)
        time.sleep(1)
        msg = "学生经验增加完毕\n"
        public.color_msg(32, msg, 40)
        time.sleep(1)
        return True

    def show_stu(self):
        stu_obj = public.load_stu_obj(self.name)
        stu = "姓名：{name:*^10},经验：{exp:*^10}\n".format(name=stu_obj.name, exp=stu_obj.exp)
        public.color_msg(35, stu, 40)
